package top.songxs.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.songxs.gmall.payment.properties.AlipayProperties;
import top.songxs.gmall.payment.service.PaymentService;
import top.songxs.gmall.rabbit.constant.MqConstant;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping(value = "/api/payment")
public class PaymentController {


    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AlipayProperties alipayProperties;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @GetMapping(value = "alipay/submit/{orderId}")
    public String payMoneyPage(@PathVariable(value = "orderId") Long orderId) {
        //  调用支付宝支付接口，得到支付提交表单html数据，并进行返回
        String result = paymentService.payMoney(orderId);
        return result ;
    }

    @PostMapping("/alipayNotify")
    public String alipayNotify(@RequestParam Map<String,String> params){
        String jsonString = JSON.toJSONString(params);

        //进行验签
        try {
            boolean result = AlipaySignature.rsaCheckV1(params,
                    alipayProperties.getPublicKey(),
                    alipayProperties.getCharSet(),
                    alipayProperties.getSignType()
            );
            System.out.println(result);
            if (result){
                //支付平台返回结果校验成功
                //发送消息通知，库存系统
                rabbitTemplate.convertAndSend(MqConstant.ORDER_EXCHANGE_NAME,MqConstant.PAYED_ROUTING_KEY,jsonString);
                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //校验失败，数据被篡改
        log.info("支付平台返回结果失败！");

        return "error" ;
    }























}
